package br.org.etec.dotcao.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import br.org.etec.dotcao.dao.Dao;

public class JPAImpl<T> implements Dao<T> {
	
	private Class<T> type;
	protected EntityManager em;
	
	public JPAImpl(Class<T> type) {
		super();
		this.type = type;
	}

	public void setEntityManager(EntityManager em) {
		this.em = em;
		System.out.println("Entity Manager atual: " + em);
	}

	@Override
	public void insert(final T element) {
		runInTransactionScope(new Runnable() {
			@Override
			public void run() {
				em.persist(element);
			}
		});
	}

	@Override
	public void update(final T element) {
		runInTransactionScope(new Runnable() {
			@Override
			public void run() {
				em.merge(element);
			}
		});
	}

	@Override
	public void delete(final T element) {
		runInTransactionScope(new Runnable() {
			@Override
			public void run() {
				em.remove(element);
			}
		});
	}

	@Override
	public T get(Long code) {
		return em.find(type, code);
	}

	@Override
	public List<T> all() {
		String jpql = "select e from " + type.getSimpleName() + " e";
		
		return em.createQuery(jpql, type).getResultList();
	}
	
	private void runInTransactionScope(Runnable runnable){
		EntityTransaction transaction = em.getTransaction();
		
		try {
			boolean endTransaction = !transaction.isActive();
			
			if(!transaction.isActive()){
				transaction.begin();
			}
			
			runnable.run();
			
			if(endTransaction && transaction.isActive()){
				transaction.commit();
			}
		} catch (Exception e) {
			if(transaction.isActive()){
				transaction.rollback();
			}
			
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void close() {
		if(em != null){
			em.close();
		}
	}

}
